package com.common.base.app.extras

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Editable
import android.text.TextPaint
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.LinearInterpolator
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.common.base.utils.AppUtils
import com.common.base.utils.AppUtils.getDrawable
import com.common.base.utils.SimpleTextWatcher
import com.common.base.utils.ViewUtils
import com.common.base.widget.RoundViewOutlineProvider
import kotlin.math.abs

/**
 * 获取全局的Context
 */
fun getContext(): Context {
    return AppUtils.getContext()
}

/**
 * dp to px
 */
fun dp2px(dipValue: Int): Int {
    val scale = getContext().resources.displayMetrics.density
    return (dipValue * scale + 0.5f).toInt()
}

fun dpDimenPx(dimenResId: Int): Float {
    return ViewUtils.getScreenAdapterDimenPx(dimenResId)
}

fun dp2px(dipValue: Float): Float {
    val scale = getContext().resources.displayMetrics.density
    return dipValue * scale + 0.5f
}

/**
 * px to dip
 */
fun px2dp(pxValue: Int): Int {
    val scale = getContext().resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

fun px2dp(pxValue: Float): Float {
    val scale = getContext().resources.displayMetrics.density
    return pxValue / scale + 0.5f
}

/**
 * 获取主题颜色的Drawable
 */
fun getImageThemeDrawable(context: Context?, resId: Int, color: Int): Drawable? {
    var drawable = getDrawable(resId)?.mutate()
    if (drawable != null) {
        drawable = DrawableCompat.wrap(drawable)
        context?.let {
            if (color != 0) {
                DrawableCompat.setTint(drawable, color)
            }
        }
    }
    return drawable
}

/**
 * 显示view
 */
fun View?.visible() {
    if (this?.visibility != View.VISIBLE) {
        this?.visibility = View.VISIBLE
    }
}

/**
 * 隐藏view
 */
fun View?.gone() {
    if (this?.visibility != View.GONE) {
        this?.visibility = View.GONE
    }
}

/**
 * 占位隐藏view
 */
fun View?.invisible() {
    this?.visibility = View.INVISIBLE
}

/**
 * 显示view，带有渐显动画效果。
 *
 * @param duration 毫秒，动画持续时长，默认500毫秒。
 */
fun View?.visibleAlphaAnimation(duration: Long = 500L) {
    this?.visibility = View.VISIBLE
    this?.startAnimation(AlphaAnimation(0f, 1f).apply {
        this.duration = duration
        fillAfter = true
    })
}


/**
 * 隐藏view，带有渐隐动画效果。
 *
 * @param duration 毫秒，动画持续时长，默认500毫秒。
 */
fun View?.goneAlphaAnimation(duration: Long = 500L) {
    this?.visibility = View.GONE
    this?.startAnimation(AlphaAnimation(1f, 0f).apply {
        this.duration = duration
        fillAfter = true
    })
}


/**
 * 占位隐藏view，带有渐隐动画效果。
 *
 * @param duration 毫秒，动画持续时长，默认500毫秒。
 */
fun View?.invisibleAlphaAnimation(duration: Long = 500L) {
    this?.visibility = View.INVISIBLE
    this?.startAnimation(AlphaAnimation(1f, 0f).apply {
        this.duration = duration
        fillAfter = true
    })
}

fun View?.animateAlpha(alpha: Float, duration: Long = 0) {
    if (!alpha.isNaN()) {
        this?.animate()?.alpha(alpha)?.setDuration(duration)?.start()
    }
}

fun setTextViewBold(vararg view: TextView?, isBold: Boolean = true) {
    view.forEach { it?.paint?.isFakeBoldText = isBold }
}

// 添加文字渐变
fun TextView.gradient(content: String, colors: IntArray) {
    val tvPaint: TextPaint = this.paint
    val width = tvPaint.measureText(content)
    val fontMetrics = tvPaint.fontMetrics
    val textTimeHei = abs(fontMetrics.top) - fontMetrics.bottom
    val textShader: Shader = LinearGradient(
        0f, 0f, width, textTimeHei, colors, null, Shader.TileMode.CLAMP
    )
    tvPaint.shader = textShader
    this.setTextColor(colors[0])        // 设置起始颜色，不然有一层白色遮罩
}

fun TextView.gradient(content: String) {
    gradient(
        content, intArrayOf(
            Color.parseColor("#90FF4A4A"),
            Color.parseColor("#FF4A4A")
        )
    )
}

/**
 * 查找RecyclerView 第一个显示的item 下标
 */
fun RecyclerView?.findFistItemPosition(): Int {
    var layoutManager: LinearLayoutManager? = null
    this?.layoutManager?.let {
        layoutManager = it as? LinearLayoutManager
    }
    val position = layoutManager?.findFirstVisibleItemPosition()
    return position ?: 0
}

fun TextView.content(): String {
    return this.text.toString().trim()
}

fun EditText.isValueOk(minLengthLimit: Int, valueOk: (res: Boolean) -> Unit) {
    addTextChangedListener(object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable?) {
            val temp = s.toString()
            valueOk(temp.length >= minLengthLimit)
        }
    })
}

fun TextView.contentAcc(): String {
    return this.text.toString().trim().replace(" ", "")
}

//文本下划线
fun TextView.underline() {
    this.paint.flags = Paint.UNDERLINE_TEXT_FLAG
    this.paint.isAntiAlias = true
}

/**
 * 设置view圆角
 */
fun View.setCorner(radius: Float) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        this.clipToOutline = true
        this.outlineProvider = RoundViewOutlineProvider(dp2px(radius))
    }
}

fun View.enable(et: EditText, method: () -> Boolean) {
    val btn: View = this
    et.addTextChangedListener(object : SimpleTextWatcher() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            btn.isEnabled = method()
        }
    })
}

fun View.setVisible(visible: Boolean) {
    visible.yes { this.visible() }.otherwise { this.gone() }
}

fun View.setGone(gone: Boolean) {
    gone.yes { this.gone() }.otherwise { this.visible() }
}

fun View.setInvisible(invisible: Boolean) {
    invisible.yes { this.invisible() }.otherwise { this.visible() }
}

//呼吸动画
fun View.breathAnim(): AnimatorSet {
    val anim1 = ObjectAnimator.ofFloat(this, "scaleX", 1.0f, 0.8f)
    val anim2 = ObjectAnimator.ofFloat(this, "scaleY", 1.0f, 0.8f)
    val sets = AnimatorSet()
    sets.playTogether(anim1, anim2)
    sets.interpolator = LinearInterpolator()
    sets.duration = 800
    anim1.repeatMode = ValueAnimator.REVERSE
    anim2.repeatMode = ValueAnimator.REVERSE
    anim1.repeatCount = ValueAnimator.INFINITE
    anim2.repeatCount = ValueAnimator.INFINITE
    sets.start()
    return sets
}

//摇晃动画
fun View.shake(): AnimatorSet {
    val animatorX = ObjectAnimator.ofFloat(this, "scaleX", 1f, 1.08f, 1f)
    val animatorY = ObjectAnimator.ofFloat(this, "scaleY", 1f, 1.08f, 1f)
    val rotation = ObjectAnimator.ofFloat(this, "rotation", 0f, 15f, 0f, -15f, 0f, 12f, 0f, -12f, 0f, 9f, 0f, -9f, 0f, 6f, 0f, -6f, 0f, 3f, 0f, -3f, 0f)
    val animatorSet = AnimatorSet()
    animatorSet.playTogether(animatorX, animatorY, rotation)
    animatorSet.duration = 600
    animatorSet.interpolator = LinearInterpolator()
    animatorSet.startDelay = 1200
    var cancel = false
    animatorSet.addListener(object : AnimatorListenerAdapter() {
        override fun onAnimationEnd(animation: Animator) {
            super.onAnimationEnd(animation)
            if (!cancel) {
                animatorSet.start()
            }
        }

        override fun onAnimationCancel(animation: Animator) {
            super.onAnimationCancel(animation)
            cancel = true
        }
    })
    animatorSet.start()
    return animatorSet
}